package com.hdmp.auth.util;

import com.hdmp.auth.entity.SysUserEntity;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.crypto.RandomNumberGenerator;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;

/**
 * @author BigFan
 * @create 2018/11/14 7:51 PM
 */
public class PasswordHelper {
    private RandomNumberGenerator randomNumberGenerator = new SecureRandomNumberGenerator();
    private String algorithmName = "md5";
    private int hashIterations = 2;


    public void setRandomNumberGenerator(RandomNumberGenerator randomNumberGenerator) {
        this.randomNumberGenerator = randomNumberGenerator;
    }

    public void setAlgorithmName(String algorithmName) {
        this.algorithmName = algorithmName;
    }

    public void setHashIterations(int hashIterations) {
        this.hashIterations = hashIterations;
    }

    public void encrptPassword(SysUserEntity userEntity) {
        if (StringUtils.isEmpty(userEntity.getSalt())) {
            userEntity.setSalt(randomNumberGenerator.nextBytes().toHex());
        }

        String newPassword = new SimpleHash(algorithmName, userEntity.getPassword()
                , ByteSource.Util.bytes(userEntity.getCredentialsSalt()), hashIterations).toHex();
        userEntity.setPassword(newPassword);

    }

}
